package com.daotu.psy.gateway.filter;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.daotu.psy.gateway.config.GatewayConfigProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.daotu.psy.common.core.constant.CacheConstants;
import com.daotu.psy.common.core.constant.SecurityConstants;
import com.daotu.psy.common.core.exception.ValidateCodeException;
import com.daotu.psy.common.core.util.R;
import com.daotu.psy.common.core.util.WebUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * The type Validate code gateway filter.
 *
 * @author lengleng
 * @date 2018 /7/4 验证码处理
 */
@Slf4j
@RequiredArgsConstructor
public class ValidateCodeGatewayFilter extends AbstractGatewayFilterFactory<Object> {

	private final GatewayConfigProperties configProperties;

	private final ObjectMapper objectMapper;

	private final RedisTemplate<String, Object> redisTemplate;

	/**
	 * 应用网关过滤器
	 * @param config 配置对象
	 * @return 网关过滤器
	 */
	@Override
	public GatewayFilter apply(Object config) {
		return (exchange, chain) -> {
			ServerHttpRequest request = exchange.getRequest();
			boolean isAuthToken = CharSequenceUtil.containsAnyIgnoreCase(request.getURI().getPath(),
					SecurityConstants.OAUTH_TOKEN_URL);

			if (!isAuthToken || isRefreshTokenRequest(request)) {
				return chain.filter(exchange);
			}

			boolean isIgnoreClient = configProperties.getIgnoreClients().contains(WebUtils.getClientId(request));
			try {
				if (!isIgnoreClient) {
					checkCode(request);
				}
			}
			catch (Exception e) {
				ServerHttpResponse response = exchange.getResponse();
				response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
				response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

				final String errMsg = e.getMessage();
				return response.writeWith(Mono.create(monoSink -> {
					try {
						byte[] bytes = objectMapper.writeValueAsBytes(R.failed(errMsg));
						DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);

						monoSink.success(dataBuffer);
					}
					catch (JsonProcessingException jsonProcessingException) {
						log.error("对象输出异常", jsonProcessingException);
						monoSink.error(jsonProcessingException);
					}
				}));
			}

			return chain.filter(exchange);
		};
	}

	/**
	 * 判断是否为刷新令牌请求
	 * @param request HTTP请求
	 * @return 是否为刷新令牌请求
	 */
	private boolean isRefreshTokenRequest(ServerHttpRequest request) {
		return StrUtil.equals(SecurityConstants.REFRESH_TOKEN, request.getQueryParams().getFirst("grant_type"));
	}

	/**
	 * 检查验证码
	 * @param request HTTP请求
	 * @throws ValidateCodeException 验证码异常
	 */
	@SneakyThrows
	private void checkCode(ServerHttpRequest request) {
		String code = request.getQueryParams().getFirst("code");

		if (CharSequenceUtil.isBlank(code)) {
			throw new ValidateCodeException("验证码不能为空");
		}

		String randomStr = StrUtil.blankToDefault(request.getQueryParams().getFirst("randomStr"),
				request.getQueryParams().getFirst(SecurityConstants.SMS_PARAMETER_NAME));

		String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;

		Object codeObj = redisTemplate.opsForValue().get(key);

		if (ObjectUtil.isEmpty(codeObj) || !code.equals(codeObj)) {
			throw new ValidateCodeException("验证码不合法");
		}

		redisTemplate.delete(key);
	}

}
